package com.suse.common.config.log;

import com.alibaba.fastjson.JSONObject;
import com.suse.common.util.request.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.suse.common.config.log.Log)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        long begin = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        doLog(pjp,end - begin);
        return result;
    }

    @Async
    public void doLog(ProceedingJoinPoint pjp, long time) {

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Log logAnnotation = method.getAnnotation(Log.class);
        log.info("============ LOG START ===============");
        log.info("模块 : {}",logAnnotation.module());
        log.info("操作 : {}",logAnnotation.operation());

        //请求的方法名
        String className = pjp.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("请求方法 : {}",className + "." + methodName + "()");

        //请求的参数
        Object[] args = pjp.getArgs();
        String params = JSONObject.toJSONString(args);
        log.info("请求参数 : {}",params);

        // 获取请求 IP
        log.info("IP地址 : {}", RequestUtil.getIp());

        // 获取请求 UserAgent
        log.info("操作系统 : {}", RequestUtil.getSystem());
        log.info("浏览器 : {}", RequestUtil.getBrowser());

        log.info("excute time : {} ms",time);
        log.info("============ LOG END ===============");

    }

}
